import moment from 'moment';
import { Attendance, User, Member } from '../models';
import { continueDays } from '../utils/common';

export default function (router) {
  router.get('/api/front/attendance/sign', async (ctx, next) => {
    if (!ctx.state.user) {
      await ctx.noLogin();
      next();
      return;
    }
    const { userid } = ctx.state.user;
    // 查找是否存在签到记录
    const hisAttendance = await Attendance.findOne({ userid });
    const nowDate = moment().format('YYYY/MM/DD');
    if (hisAttendance) {
      // 计算连续签到次数
      let keepTimes = continueDays(hisAttendance.records);
      let records = hisAttendance.records || [];
      if (hisAttendance.records.indexOf(nowDate) < 0) {
        ++keepTimes;
        records.push(nowDate);
      }
      const updateResult = await Attendance.updateOne({ userid }, { $addToSet: { records: moment().format('YYYY/MM/DD') }, keep_times: keepTimes });
      if (updateResult.ok == 1 && updateResult.nModified == 1) {
        /**
         * 发放奖励
         * 每天签到成功可以领取15书币
         * 连续签到3天 额外获得30书币
         * 连续签到7天 额外获得45书币, 并获得 3 天体验会员
         * 连续签到15天 额外获得60书币
         * 连续签到30天 额外获得90书币
         */
        let basePrise = 15;
        switch (keepTimes) {
          case 3:
            basePrise += 30;
            break;
          case 7:
            basePrise += 45;
            // 送会员，如果当前存在永久会员，则不设置
            // eslint-disable-next-line no-case-declarations
            const curMemberInfo = await Member.findOne({ userid });
            if (!curMemberInfo) {
              await Member.setMember({
                userid,
                memberName: '3天体验会员',
                source: 'attendance-give'
              });
            } else {
              const curExpiredTime = curMemberInfo.expired || 0;
              const newExpiredTime = curExpiredTime + 3 * 24 * 60 * 60 * 1000;
              await Member.updateOne({ userid }, { $set: { expired: newExpiredTime } });
            }
            break;
          case 15:
            basePrise += 60;
            break;
          case 30:
            basePrise += 90;
            break;
        }
        // 修改用户的书币数
        const changeResult = await User.addAmount(userid, basePrise, '发放签到奖励');
        if (changeResult) {
          await ctx.json(true, '签到成功', { keepTimes, records, prise: basePrise, isThreeDay: keepTimes === 7 });
        } else {
          // 回退签到记录
          const hisNewAttendance = await Attendance.findOne({ userid: userid });
          const records = hisNewAttendance.records.filter(item => {
            return item !== nowDate;
          });
          await Attendance.updateOne({ userid }, { $set: { records, keep_times: continueDays(records) } });
          await ctx.json(false, '发放奖励失败');
        }
      } else {
        await ctx.json(false, '您已经签到过了');
      }
    } else {
      const thisAttendance = await Attendance.create({
        userid: ctx.transId(userid),
        keep_times: 1,
        records: [moment().format('YYYY/MM/DD')],
        create_time: new Date()
      });
      if (thisAttendance) {
        const basePrise = 5;
        const changeResult = await User.addAmount(userid, basePrise, '发放签到奖励');
        if (changeResult) {
          await ctx.json(true, '签到成功', { keepTimes: 1, records: thisAttendance.records });
        } else {
          const hisNewAttendance = await Attendance.findOne({ userid: userid });
          const records = hisNewAttendance.records.filter(item => {
            return item !== nowDate;
          });
          await Attendance.updateOne({ userid: userid }, { $set: { records } });
          await ctx.json(false, '发放奖励失败');
        }
      } else {
        await ctx.json(false, '保存签到记录失败');
      }
    }
  });

  // 获取我的签到信息
  router.get('/api/front/attendance/me', async (ctx, next) => {
    if (!ctx.state.user) {
      await ctx.noLogin();
      next();
      return;
    }
    const { userid } = ctx.state.user;
    const hisAttendance = await Attendance.findOne({ userid });
    await ctx.json(true, 'success', {
      keepTimes: hisAttendance ? hisAttendance.keep_times : 0,
      records: hisAttendance ? hisAttendance.records : []
    });
  });
}
